﻿using UnityEngine;

namespace HBFramework
{

    public enum AudioPlayerType
    {
        Music = 1,
        Sound = 2,
    }

    /// <summary>
    /// 音频播放器
    /// </summary>
    public class AudioPlayer : IObjectPoolItem
    {
        public AudioPlayerType playerType;

        private AudioSource audioSource;

        private float playerVolume;

        public void OnCreate(params object[] args)
        {
            GameObject audioPlayer = new GameObject("AudioPlayer");
            GameObject.DontDestroyOnLoad(audioPlayer);
            audioSource = audioPlayer.AddComponent<AudioSource>();
            audioSource.playOnAwake = false;
        }

        public void OnRecycle()
        {
            if (audioSource != null)
            {
                audioSource.Stop();
                audioSource.gameObject.SetActive(false);
            }
        }

        public void OnRelease()
        {
            GameObject.Destroy(audioSource);
        }

        public void OnRent(params object[] args)
        {
            audioSource.gameObject.SetActive(true);
        }

        /// <summary>
        /// 播放音频
        /// </summary>
        /// <param name="clip"></param>
        /// <param name="volume"></param>
        /// <param name="isLoop"></param>
        public void Play(AudioClip clip, float volume, bool isLoop)
        {
            playerVolume = volume;
            audioSource.clip = clip;
            audioSource.loop = isLoop;

            RefreshVolume();
            audioSource.gameObject.SetActive(true);
            audioSource.Play();
        }

        /// <summary>
        /// 是否正在播放
        /// </summary>
        /// <returns></returns>
        public bool IsPlaying()
        {
            //return audioSource.isPlaying && audioSource.volume > 0.001f;
            return audioSource.isPlaying;
        }

        /// <summary>
        /// 刷新音量
        /// </summary>
        public void RefreshVolume()
        {
            switch (playerType)
            {
                case AudioPlayerType.Music:
                    audioSource.volume = playerVolume * AudioManager.Instance.MusicVolume / 100;
                    break;
                case AudioPlayerType.Sound:
                    audioSource.volume = playerVolume * AudioManager.Instance.SoundVolume / 100;
                    break;
                default:
                    break;
            }
        }
    }
}